package hotel.quartz.oversea.job.switchs;

import hotel.base.oversea.constant.CommonConstants;
import hotel.base.oversea.constant.CommonUrlConstants;
import hotel.base.oversea.constant.MeituanConstants;
import hotel.base.oversea.constant.enums.MessageEnums;
import hotel.base.oversea.constant.quartz.UrlSwitchsEnums;
import hotel.base.oversea.utils.DateUtil;
import hotel.base.oversea.utils.GsonUtils;
import hotel.base.oversea.utils.Result;
import hotel.base.oversea.utils.SendUtils;
import hotel.quartz.oversea.config.service.RedisService;
import hotel.quartz.oversea.job.base.BaseJob;
import hotel.quartz.oversea.job.task.SwUpdateCancelTask;
import hotel.quartz.oversea.util.JobRestTemplateUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;

/**
 * <p>
 *     美团_每半小时_处理失效产品队列
 *
 *
 *  消费队列 - 产品变更 -  产品失效队列  包含（1、失效新增房型的产品  2、全日房变为钟点房  3、产品没有在酒店产品里失效了 4 5 6
 *
 *                         房型失效(新增)  推送给携程，和产品失效是同一个接口，接口有限制，所以等失效队列处理完再处理房型失效队列 ---》》所以房型和产品失效队列放在一个job进行处理
 *
 *
 * </p>
 *
 * @description: todo Switchs Pop Queue Basic Goods Change Job
 * @author: qiuyy
 * @date: 2020-05-26 13:22
 * @version: V1.0
 */
@Slf4j
public class PartTimeSwitchsPopQueueFailureGoodsJob implements BaseJob {
    private String timestamp = "Tsgcrdtpj"+String.valueOf(System.currentTimeMillis());

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private RedisService redisService;

    @Autowired
    private SwUpdateCancelTask swUpdateCancelTask;

    public static void main(String[] args) {
        String now = DateUtil.getCurrTime();
        String hours = now.split(" ")[1].split(":")[0];

        System.out.printf("=="+hours+"==");
    }
    /**
     *  每半小时
     *
     * @param jobExecutionContext
     */
    @Override
    @SneakyThrows
    public void execute(JobExecutionContext jobExecutionContext) {
        String now = DateUtil.getCurrTime();
        log.info("todo Switchs Pop Queue Basic Goods Change Job {} >>>>>>>> 携程消费队列处理静态产品早餐失效新增定时器 执行时间: {}", timestamp,now);
        Long sizeDown = redisService.queueSize(MeituanConstants.REDIS_QUEUE_HOTEL_DOWN_GOODS_JSON_KEY);


        if(null == redisService.get("PartTimeSwitchsPopQueueFailureGoodsJob_cancel_close")){
            try{
                swUpdateCancelTask.executeUpdateCancel();
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        if(null == redisService.get("PartTimeSwitchsPopQueueFailureGoodsJob_requestDown_close")){
            if(sizeDown==0){
                log.info("todo Switchs Pop Queue Basic Goods Change Job {} >>>>>>>> 失效队列size=0，不触发推送失效携程: {},{}",timestamp, DateUtil.getCurrTime());
            }else{
                try {
                    Thread.sleep(3000);
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
                Long newSizeDown = redisService.queueSize(MeituanConstants.REDIS_QUEUE_HOTEL_DOWN_GOODS_JSON_KEY);
                if(BigDecimal.valueOf(newSizeDown).compareTo(BigDecimal.valueOf(sizeDown))>=0){//大于时表示 校验在push 队列在增加，所以定时器执行
                    SendUtils.dingMsgNotLog("[FAIL-GOODS-SW]", DateUtil.getCurrTime()+" 程序判断队列大于0,newSizeDown="+newSizeDown+",sizeDown="+sizeDown+"当前可继续执行失效产品", MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
                    requestDown();
                }else{
                    SendUtils.dingMsgNotLog("[FAIL-GOODS-SW]", DateUtil.getCurrTime()+" 上一个程序还在执行中，当前批次不执行处理携程失效产品", MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
                    return;
                }
            }
        }
        //按顺序down处理完再处理房型的失效
        if(null == redisService.get("PartTimeSwitchsPopQueueFailureGoodsJob_pushRoomUpdate_close")){
            failreNewAddRoomPushSw();//房型失效  推送给携程，和产品失效是同一个接口，接口有限制，所以等失效队列处理完再处理房型失效队列 -->(包含新增和失效，同一个接口推送)
        }

        log.info("todo Switchs Pop Queue Basic Goods Change Job {} >>>>>>>> 携程消费队列处理静态产品早餐失效新增定时器 结束时间: {},{}",timestamp, DateUtil.getCurrTime());

    }

    private void requestDown() {
       // String host = CommonUrlConstants.SWITCHS_HOST;
        String host = CommonUrlConstants.SWITCHS_ONLINE_HOST;
        String url = host+ UrlSwitchsEnums.addDowngGoods.DOWN.getValue();
        log.info("todo Switchs Pop Queue Basic Goods Change Job {} 携程消费队列处理静态产品早餐失效新增定时器 进入方法 requestDown",timestamp);

        long size = redisService.queueSize(MeituanConstants.REDIS_QUEUE_HOTEL_DOWN_GOODS_JSON_KEY);
        Integer successCount = 0;
        if(size>0){
            Long useTime = 1L;
            if(size*(1*6*3+1)/60!=0){
                useTime = size*(1*6*3+1)/60;
            }
            SendUtils.dingMsgNotLog("[JOB-POP] 即将执行消费队列，携程处理失效产品 ", DateUtil.getCurrTime()+" 酒店队列："+size+" 预计耗时："+useTime+" 分钟", MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
            try {
                Thread.sleep(5000);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            for (int i = 0; i < size; i++) {
                String oneHotelJOSN = (String)redisService.RPop(MeituanConstants.REDIS_QUEUE_HOTEL_DOWN_GOODS_JSON_KEY);
                if(!ObjectUtils.isEmpty(oneHotelJOSN)){
                    //发起请求
                    log.info("requestDown todo Switchs Pop Queue Basic Goods Change Job 调用失效接口前 酒店产品队列："+redisService.queueSize(MeituanConstants.REDIS_QUEUE_HOTEL_DOWN_GOODS_JSON_KEY));
                    Result response = JobRestTemplateUtils.post(url,oneHotelJOSN,restTemplate);
                    long size2 = redisService.queueSize(MeituanConstants.REDIS_QUEUE_HOTEL_DOWN_GOODS_JSON_KEY);
                    log.info("requestDown todo Switchs Pop Queue Basic Goods Change Job {} 调用失效接口  requestDown 调用携程接口结束，缓存队列size={}",timestamp,size2);
                    if(response.getCode()!= CommonConstants.SUCCESS){
                        log.error("requestDown todo Switchs Pop Queue Basic Goods Change Job 异常  失效  当前酒店推送携程失败：rs={}", GsonUtils.GsonString(response));
                        SendUtils.dingMsg("'失效'产品！推送携程失败 ", DateUtil.getCurrTime()+" 推送内容："+oneHotelJOSN+" 接口返回异常:"+ GsonUtils.GsonString(response), MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
                    }else{
                        successCount+=1;
                        log.info("requestDown todo Switchs Pop Queue Basic Goods Change Job '失效'产品 推送携程成功:"+response);
                        //SendUtils.dingMsg("查询到'失效'产品,推送成功 ",DateUtil.getCurrTime()+" 内容："+oneHotelJOSN, MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
                    }
                    if(null != redisService.get("PartTimeSwitchsPopQueueFailureGoodsJob_requestDown_close")){
                        log.info("requestDown todo Switchs Pop Queue Basic Goods Change Job    主动停止失效推送  ");
                        break;
                    }
                    Integer time = 6000*3+1000;
                    if(null != redisService.get("requestDown_time")){
                        time = (Integer)redisService.get("requestDown_time");
                    }
                    try {
                        Thread.sleep(time);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }
            }
            //if(BigDecimal.valueOf(successCount).compareTo(BigDecimal.valueOf(size))!=0){
               // SendUtils.dingMsgNotLog("[JOB-POP-FAIL] 定时器结束执行！携程消费队列处理失效产品 ",DateUtil.getCurrTime()+" 已处理数据："+successCount+" 数据数量处理'异常'实际应处理："+size, MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
           // }else{
                SendUtils.dingMsgNotLog("[JOB-POP-FAIL] 定时器结束执行！携程消费队列处理失效产品 ", DateUtil.getCurrTime()+" 处理完成酒店队列："+successCount, MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
           // }
        }

        log.info("requestDown todo Switchs Pop Queue Basic Goods Change Job 结束 失效产品 推携程");

    }

    private void failreNewAddRoomPushSw() {

        //失效产品队列执行结束后，判断，房型变更队列是否有需要处理
        log.info("失效产品队列执行结束后，判断，房型变更队列是否有需要处理");
        long roomSize = redisService.queueSize(MeituanConstants.REDIS_QUEUE_BASIC_REAL_ROOM_UPDATE_TO_SWITCHS);
        Integer successCountChange = 0;
        if(roomSize>0){

            Long useTime = 1L;
            if(roomSize*(1*6*3+1)/60!=0){
                useTime = roomSize*(1*6*3+1)/60;
            }
            SendUtils.dingMsgNotLog("[JOB-CHANGE-ROOM-POP] 即将执行消费队列，携程处理失效和新增房型产品 ", DateUtil.getCurrTime()+" 酒店队列："+roomSize+" 预计耗时："+useTime+" 分钟", MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
            try {
                Thread.sleep(5000);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }

            for (int i = 0; i < roomSize; i++) {
                //pop数据
                String hotelGoodsRoomInfoJson = (String)redisService.RPop(MeituanConstants.REDIS_QUEUE_BASIC_REAL_ROOM_UPDATE_TO_SWITCHS);
                if(null != hotelGoodsRoomInfoJson){
                    //发起请求
                   /* String url = CommonUrlConstants.SWITCHS_HOST+"/switchCreateRoom/roomFailure";//该方法为失效新增房型统一方法*/
                    String url = CommonUrlConstants.SWITCHS_ONLINE_HOST+"/switchCreateRoom/roomFailure";
                    log.info("requestDown todo Switchs Pop Queue Basic Goods Change Job 调用失效新增房型接口前 酒店产品队列："+redisService.queueSize(MeituanConstants.REDIS_QUEUE_BASIC_REAL_ROOM_UPDATE_TO_SWITCHS));
                    Result response = JobRestTemplateUtils.post(url,hotelGoodsRoomInfoJson,restTemplate);
                    long size2 = redisService.queueSize(MeituanConstants.REDIS_QUEUE_BASIC_REAL_ROOM_UPDATE_TO_SWITCHS);
                    log.info("requestDown todo Switchs Pop Queue Basic Goods Change Job {} 失效新增房型  requestDown 调用携程接口结束，缓存队列size={}",timestamp,size2);
                    if(response.getCode()!= CommonConstants.SUCCESS){
                        log.error("requestDown todo Switchs Pop Queue Basic Goods Change Job 异常  失效新增房型  当前酒店推送携程失败：rs={}", GsonUtils.GsonString(response));
                        SendUtils.dingMsg("失效新增房型！推送携程失败 ", DateUtil.getCurrTime()+" 推送内容："+hotelGoodsRoomInfoJson+" 接口返回异常:"+ GsonUtils.GsonString(response), MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
                    }else{
                        successCountChange+=1;
                        log.info("requestDown todo Switchs Pop Queue Basic Goods Change Job '失效新增房型'产品 推送携程成功:"+response);
                        //SendUtils.dingMsg("查询到'失效'产品,推送成功 ",DateUtil.getCurrTime()+" 内容："+oneHotelJOSN, MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
                    }
                    if(null != redisService.get("PartTimeSwitchsPopQueueFailureGoodsJob_pushRoomUpdate_close")){
                        log.info("requestDown todo Switchs Pop Queue Basic Goods Change Job    主动停止失效新增房型推送  ");
                        break;
                    }
                    Integer time = 6000*3+1000;
                    if(null != redisService.get("requestChange_time")){
                        time = (Integer)redisService.get("requestChange_time");
                    }
                    try {
                        Thread.sleep(time);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }

                }else{
                    log.info("for结束，当前房型变更队列已无数据");
                }
            }
            SendUtils.dingMsgNotLog("[JOB-POP-CHANGE] 定时器结束执行！携程处理失效新增房型 ", DateUtil.getCurrTime()+" 处理完成酒店队列："+successCountChange, MessageEnums.genre.GOODS_STATUS_AND_PRICE.getCode(),restTemplate);
        }else{
            log.info("无需处理的 失效新增房型队列");
        }

    }

}
